package com.mfnote.view.hand;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.mfnote.adapter.NewHandAdapter;
import com.mfnote.db.dao.HandDao;
import com.mfnote.model.HandEntity;
import com.mfnote.util.FinalData;
import com.mfnote.view.R;
import com.mfnote.view.R.anim;
import com.mfnote.view.R.drawable;
import com.mfnote.view.R.id;
import com.mfnote.view.R.layout;
import com.mfnote.view.R.raw;
import com.mfnote.view.other.MyApplication;

/**
 * 手绘界面
 * @author DC
 *
 */
public class NewHandActivity extends Activity implements OnItemClickListener {
	//手绘的文件的标题
	private EditText newhand_et_title_name = null;
	//手势的绘制位置
	private GestureOverlayView gestures = null;
	//加载底部的菜单
	private GridView newhand_gv_bottom_menu = null;
	//显示识别出图形的标准的图形的LinearLayout
	private LinearLayout show_image = null;
	//显示识别出图形的标准的图形
	private ImageView standard_image = null;
    //手势库
	private GestureLibrary gestLibrary = null;
	//识别出图形对应的ID
	private int identifyImageID = FinalData.IMAGE_CIRCLE;
	//时间值
	private String time="";
	//保存文件名
	private String fileName = "";
	//获得传过来的手绘的信息
	private HashMap<String,Object> map = null;
	//是否完成识别
	private boolean isIdentify = false;
	//是否保存的标志
	private boolean isSave = false;
	//各种图形的名称
	private String[] shapes ={"圆","表格","矩形","方形","矩形","三角形","三角形"};
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			switch (msg.what) {
			case FinalData.NEWHADNACTIVITY_IDENTIFY:
				//识别成功,更新界面
				gestures.setVisibility(View.GONE);
				show_image.setVisibility(View.VISIBLE);
				//根据识别得到的名称在standard_image显示对应的图形
				showStandartImage(msg.obj);
				newhand_gv_bottom_menu.setFocusable(true);
				isIdentify = true;
				break;
			case FinalData.NEWHADNACTIVITY_NOT_SAVE:
				//不保存,更新到原来的界面
				gestures.setVisibility(View.VISIBLE);
				show_image.setVisibility(View.GONE);
				//设置在绘制手势时或之前不能点击保存或舍弃
				newhand_gv_bottom_menu.setFocusable(false);
				isIdentify = false;
				isSave =false;
				break;
			case FinalData.NEWHADNACTIVITY_NOT_NULL:
				gestures.setVisibility(View.GONE);
				show_image.setVisibility(View.VISIBLE);
				newhand_et_title_name.setText("");
				newhand_gv_bottom_menu.setFocusable(true);
				fileName = map.get("title").toString();
				//设置标题
				newhand_et_title_name.setText(fileName);
				newhand_et_title_name.setSelection(fileName.length());
				//获得上次保存的时间
				time = map.get("time").toString();
				//根据识别得到的名称在standard_image显示对应的图形
				String imageID = map.get("imagePath").toString();
				showStandartImage(shapes[Integer.parseInt(imageID)]);
				isIdentify = true;
				isSave = true;
				break;
			}
		}

	

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newhand);
		MyApplication.getInstance().addActivity(this);
		newhand_et_title_name = (EditText) findViewById(R.id.newhand_et_title_name);

		newhand_gv_bottom_menu = (GridView) findViewById(R.id.newhand_gv_bottom_menu);
		show_image = (LinearLayout) findViewById(R.id.show_image);
		standard_image = (ImageView) findViewById(R.id.standard_image);

		// 加载资源
		gestLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);

		if (gestLibrary.load()) {
			// 加载成功处理
			loadLibrary();
		} else {
			// 加载失败
			Toast.makeText(this, "手势库加载失败", Toast.LENGTH_SHORT).show();
		}
		newhand_gv_bottom_menu.setSelector(new ColorDrawable(Color.TRANSPARENT));  //去掉自身自带的按下背景效果
		newhand_gv_bottom_menu.setAdapter(new NewHandAdapter(this));
		newhand_gv_bottom_menu.setOnItemClickListener(this);
		//设置在绘制手势时或之前不能点击保存或舍弃
		newhand_gv_bottom_menu.setFocusable(false);
		
		Intent intent = this.getIntent();
		
		map =(HashMap<String, Object>) intent.getSerializableExtra("map");
		if(map==null){
			//未带数据,不做处理
		}else{
			//通知主线程更新到已经识别出的界面
			Message msg = new Message();
			msg.what=FinalData.NEWHADNACTIVITY_NOT_NULL;
			handler.sendMessage(msg);
		}
		
	}
    
	/**加载手势库及相应的处理**/
	private void loadLibrary() {
		gestures = (GestureOverlayView) findViewById(R.id.gestures);
		gestures.addOnGesturePerformedListener(new OnGesturePerformedListener() {
			@Override
			public void onGesturePerformed(GestureOverlayView overlay,Gesture gesture) {
				ArrayList<Prediction> predictions = gestLibrary.recognize(gesture);
				if(predictions.size()>0){
					 Prediction prediction = predictions.get(0);
					 if(prediction.score>1.0){
						 Log.d("names", prediction.name+"");
						 //匹配成功,通知主线程更新界面
						 Message msg = new Message();
						 msg.what =FinalData.NEWHADNACTIVITY_IDENTIFY;
						 msg.obj = prediction.name;
						 handler.sendMessage(msg);
						 fileName = createFileName();
					 }else{
						 //匹配度太低
						 Toast.makeText(getApplicationContext(), "无法识别,请重画", Toast.LENGTH_SHORT).show();
					 }
				}else{
					//手势库为空,无法识别
					Toast.makeText(getApplicationContext(), "手势库为空", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
    
	/**获得手绘图形对应的标准图形**/
	private void showStandartImage(Object obj) {
		String name = (String) obj;
		isIdentify = true;
		if(name.contains("表格")){
			Toast.makeText(this, "您所画的图形是表格", Toast.LENGTH_SHORT).show();
			standard_image.setImageResource(R.drawable.newhand_table);
			identifyImageID = FinalData.IMAGE_TABLE;
		}else if(name.contains("矩形")){
			Toast.makeText(this, "您所画的图形是矩形", Toast.LENGTH_SHORT).show();
			if(name.equals("矩形1")){
				identifyImageID = FinalData.IMAGE_RECT_HORIZONTAL;
				standard_image.setImageResource(R.drawable.newhand_rect);
			}else{
				identifyImageID = FinalData.IMAGE_RECT_VERTICAL;
				standard_image.setImageResource(R.drawable.newhand_rect2);
			}
		}else if(name.contains("圆")){
			Toast.makeText(this, "您所画的图形是圆", Toast.LENGTH_SHORT).show();
			standard_image.setImageResource(R.drawable.newhand_circle);
			identifyImageID = FinalData.IMAGE_CIRCLE;
		}else if(name.contains("方形")){
			Toast.makeText(this, "您所画的图形是方形", Toast.LENGTH_SHORT).show();
			standard_image.setImageResource(R.drawable.newhand_square);
			identifyImageID = FinalData.IMAGE_SQUARE;
		}else if(name.contains("三角形")){
			Toast.makeText(this, "您所画的图形是三角形", Toast.LENGTH_SHORT).show();
			if(name.equals("三角形1")){
				standard_image.setImageResource(R.drawable.newhand_triangle_up);
				identifyImageID = FinalData.IMAGE_TRIANGLE_UP;
			}else{
				standard_image.setImageResource(R.drawable.newhand_triangle_down);
				identifyImageID = FinalData.IMAGE_TRIANGLE_DOWN;
			}
		}
	}

	/**ListView的点击事件**/
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(!isIdentify){
			return;
		}
		switch (position) {
		case 0:
			isIdentify = false;
			//取消,通知主线程更新到原来的界面
			Message msg =new Message();
			msg.what =FinalData.NEWHADNACTIVITY_NOT_SAVE;
			handler.sendMessage(msg);
			newhand_et_title_name.setText("");
			time="";
			fileName="";
			isSave = false;
			break;
		case 1:
			//TODO 保存
			//向数据库写一条数据
			writeTOHandDB();
			break;
		}
	}
    
	/**将当前的手绘信息保存到数据库中**/
	private void writeTOHandDB() {
		String editText = newhand_et_title_name.getText().toString().trim();
		
		if(editText.equals(fileName)){
			//单击Item进来时,若用户未修改filename，则不需要保存
			Toast.makeText(this, "已经保存", Toast.LENGTH_SHORT).show();
			isSave = true;
			return ;
		}
		HandDao handDao = new HandDao(this);
		
		HandEntity handEntity = new HandEntity();
		handEntity.setImagePath(identifyImageID+"");
		handEntity.setFlag(0);
		if(editText.equals("")||editText==null){
		    handEntity.setTitle(fileName);
		}else{
			Log.d("editText", editText+"");
			long state = handDao.queryHand(editText);
			Log.d("state", state+"");
			if(state>0){
				//该名称已存在,不能保存,弹出对话框
				Toast.makeText(this, "该文件名已存在，请重新输入", Toast.LENGTH_SHORT).show();
				return;
			}
			handEntity.setTitle(editText);
		}
		createFileName() ;
		handEntity.setTime(time);
		long state = handDao.insertHand(handEntity);
		if(state>0){
			isSave = true;
			Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
			//跳转
			Intent intent =new Intent(this,HandActivity.class);
			startActivity(intent);
			this.finish();
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
		}else{
			isSave = false;
			Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
		}
	}
    
//	/**名称存在弹出的对话框 **/
//	private void titleExistDialog() {
//		AlertDialog.Builder builder = new AlertDialog.Builder(this);
//		builder.setTitle("用户已存在");
//		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//			
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				
//			}
//		});
//		builder.create().show();
//	}
    
	/**监听返回键**/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			String editText = newhand_et_title_name.getText().toString();
			Log.d("filename", editText+" "+fileName);
			if(fileName.equals(editText)){
				isSave = true;
			}
			if(isSave){
				Intent intent =new Intent(this,HandActivity.class);
				startActivity(intent);
				this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			}else{
				//弹出对话框
				isSaveDialog();
			}
			
		}
		return true;
	}
	
	/**提示用户是否保存的对话框**/
	private void isSaveDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("是否保存");
		builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		builder.setNeutralButton("保存", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//往数据库中写完后跳转
				writeTOHandDB();
			}
		});
		builder.setNegativeButton("舍弃", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//不做任何处理,直接跳转
				Intent intent = new Intent(getApplicationContext(),HandActivity.class);
				startActivity(intent);
				NewHandActivity.this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
				
			}
		});
		builder.create().show();
	}
    
	/**获得文件名**/
	private String createFileName() {
		String fileName = "";
		Date date = new Date(System.currentTimeMillis());  //系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
		fileName = dateFormat.format(date);
		dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = dateFormat.format(date);
		return fileName;
	}
	
}
